import axios from 'axios';
import { get as _get, includes } from 'lodash';
import { store } from '@src/model/index';
import * as types from '@src/model/actionType';

const METHODS = ['get', 'post'];
const DEFAULT_HEADERS = { 'X-Requested-With': 'XMLHttpRequest' };
const POST = 'post';
const GET = 'get';
const DEFAULT_METHOD = GET;
const DEFAULT_TIMEOUT = 1000 * 60;
const DEFAULT_RESPONSE_TYPE = 'json';
const LOCK_LIST = [];
const OPEN_LOCK = true;
const DEFAULT_RESOLVE = {};
const DEFAULT_BASE_URL = '';
// const HIDE_FLAG = false;
const RETURN_FLAG = false;
const DEFAULT_OPEN_LOADING = true;

function request(payload) {
  const url = _get(payload, ['url'], '');
  if (!url) {
    return Promise.resolve(DEFAULT_RESOLVE);
  }

  const method = _get(payload, ['method'], DEFAULT_METHOD).toLowerCase();
  if (!includes(METHODS, method)) {
    return Promise.resolve(DEFAULT_RESOLVE);
  }

  const params = _get(payload, ['params'], {});

  const openLock = _get(payload, ['openLock'], OPEN_LOCK);

  const returnFlag = _get(payload, ['returnFlag'], RETURN_FLAG);

  const openLoading = _get(payload, ['openLoading'], DEFAULT_OPEN_LOADING);

  const lockParamsUrl = JSON.stringify(params) + url;
  const lockParamsUrlIndex = LOCK_LIST.indexOf(lockParamsUrl);
  if (lockParamsUrlIndex > -1) {
    return Promise.resolve(DEFAULT_RESOLVE);
  }
  if (openLock) {
    LOCK_LIST.push(lockParamsUrl);
  }

  const config = {
    url,
    method,
    baseURL: _get(payload, ['baseURL'], DEFAULT_BASE_URL),
    headers: _get(payload, ['headers'], DEFAULT_HEADERS),
    timeout: _get(payload, ['timeout'], DEFAULT_TIMEOUT),
    responseType: _get(payload, ['responseType'], DEFAULT_RESPONSE_TYPE),
  };

  if (method === POST) {
    config.data = params;
  } else if (method === GET) {
    config.params = params;
  }
  if (openLoading) {
    store.dispatch({ type: types.loading, payload: { loading: true } });
  }
  return axios(config)
    .then((val) => {
      const err = _get(val, ['data', 'Response', 'Error'], null);
      const data = _get(val, ['data', 'Response'], {});
      if (!err) {
        return data;
      }
      if (returnFlag) {
        return data;
      }
      return undefined;
    })
    .catch((err) => {
      console.log(err);
      return Promise.reject('网络异常');
    })
    .finally(() => {
      const lockParamsUrlIndexs = LOCK_LIST.indexOf(lockParamsUrl);
      LOCK_LIST.splice(lockParamsUrlIndexs, 1);
      if (openLoading) {
        store.dispatch({ type: types.loading, payload: { loading: false } });
      }
    });
}

export default request;
